package project.userAED;/*
 *  @Author Mr.long
 *  @QQ 1507468405
 *  @Creat 2021/11/7 - 21:28
 */

import Utils.MyExcel;
import org.json.JSONException;
import org.json.JSONObject;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.*;

import static java.lang.System.out;

@WebServlet(value = "/userExportServlet")
public class userExportServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        service(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        service(request, response);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.service(req, resp);
        JSONObject json = Export(req,"export_user.xls");
        out.println(json);
        //将响应消息返回页面
        resp.setContentType("text/html; charset=UTF-8");
        resp.getWriter().print(json);
        resp.getWriter().flush();
        resp.getWriter().close();
    }

    public JSONObject Export(HttpServletRequest req,String filename) throws UnsupportedEncodingException {
        req.setCharacterEncoding("UTF-8");
        String encoding = req.getCharacterEncoding();
        out.println(encoding);
        JSONObject data;
        JSONObject json = new JSONObject();
        try(
                InputStreamReader isr = new InputStreamReader(req.getInputStream(),encoding);
                BufferedReader br = new BufferedReader(isr)
        ){
            StringBuffer buffer = new StringBuffer();
            String temp;
            while ((temp = br.readLine())!=null){
                buffer.append(temp);
            }
            temp = buffer.toString();
            data = new JSONObject(temp);
            MyExcel me = new MyExcel();
            //设置写入Excel文件路径
            String path = req.getSession().getServletContext().getRealPath("/")+"ExportFile\\";
            String url = req.getContextPath()+ "\\ExportFile\\";
            json.put("url", url+filename);
            json.put("file_path",path+filename);
            me.exportData(data,path,filename);
        }catch (IOException | JSONException e){
            e.printStackTrace();
        }
        return json;
    }
}
